const BaseModel = require('./base_model');

/**
 * 前端用户模型
 */

class UserModel extends BaseModel {
    constructor(data = {}) {
        super(data);
        // 用户基础信息
        this.id = data.id || data.USER_ID || '';
        this.name = data.name || data.USER_NAME || '';
        this.avatar = data.avatar || data.USER_AVATAR || '';
        this.mobile = data.mobile || data.USER_MOBILE || '';
        
        // 用户角色与权限
        this.role = data.role || '';
        this.permissions = Array.isArray(data.permissions) ? data.permissions : [];
        this.roles = Array.isArray(data.roles) ? data.roles : (data.USER_ROLES || []);
        
        // 用户组织信息
        this.department = data.department || data.USER_DEPT || '';
        this.title = data.title || '';
        this.no = data.no || '';
        
        // 用户状态
        this.status = data.status !== undefined ? data.status : 1;
        this.lastLoginTime = data.lastLoginTime || null;
        
        // 表单数据
        this.forms = Array.isArray(data.forms) ? data.forms : (data.USER_FORMS || []);
    }
    
    // 检查是否为管理员
    isAdmin() {
        return this.role === 'admin' || this.roles.includes('admin');
    }
    
    // 检查是否有特定权限
    hasPermission(permissionCode) {
        if (this.isAdmin()) return true;
        return this.permissions.includes(permissionCode);
    }
    
    // 检查是否有特定角色
    hasRole(roleCode) {
        if (this.isAdmin()) return true;
        return this.roles.includes(roleCode);
    }
    
    // 获取用户显示名称
    getDisplayName() {
        return this.name || '未命名用户';
    }
    
    // 转换为API传输格式
    toApiFormat() {
        return {
            USER_ID: this.id,
            USER_NAME: this.name,
            USER_MOBILE: this.mobile,
            USER_DEPT: this.department,
            USER_ROLES: this.roles,
            USER_FORMS: this.forms
        };
    }
    
    // 从API响应创建模型实例
    static fromApiResponse(data) {
        return new UserModel(data);
    }
}

module.exports = UserModel; 